package com.ll.test.model.user.role;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class RoleControl {
	Map<String, RoleInfo> map = new HashMap<String, RoleInfo>();

	@RequestMapping("/role")
	public String userrole(Model model) {
		List<RoleInfo> list = new ArrayList<RoleInfo>();

		for (Map.Entry<String, RoleInfo> entry : map.entrySet()) {
			list.add(entry.getValue());
		}
		model.addAttribute("roles", list);
		model.addAttribute("size", list.size());
		return "/user/admin-role";
	}

	@RequestMapping("/addrole")
	public String addrole(HttpServletRequest request, Model model) {
		String id = request.getParameter("id");
		if ("".equals(id) || null == id) {
			return "/user/admin-role-add";
		} else {
			RoleInfo role = map.get(id);
			model.addAttribute("role", role);
			return "/user/admin-role-add";

		}
	}

	@RequestMapping("/save")
	@ResponseBody
	public ResultVo saveRole(RoleInfo role) {
		if (null != role) {
			if (null == role.getId() || "".equals(role.getId())) {
				String key = String.valueOf(System.currentTimeMillis());
				role.setId(key);
				map.put(key, role);
			} else {
				map.put(role.getId(), role);
			}
			return ResultVo.success();
		} else {
			return ResultVo.msg("-1", "添加失败！");
		}
	}

	@RequestMapping("/delRole")
	@ResponseBody
	public ResultVo delRole(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (null != id && !"".equals(id)) {
			String[] ids = id.split(",");
			for (String key : ids) {
				map.remove(key);
			}
			return ResultVo.success();
		} else {
			return ResultVo.msg("-1", "删除失败！");
		}

	}
}